<?php

/**
 * 行为分析-log
 *
 * @author meng.deng
 */

require_once 'CommonController.php';

class Admin_ActMdLogController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_logModel = new Application_Model_ActMdLogEvent();
        $this->_logFieldModel = new Application_Model_ActMdLogEventField();
        $this->_logFieldLoopModel = new Application_Model_ActMdLogEventFieldLoop();
        $this->_childPactEventFieldModel = new Application_Model_ActMdChildPactEventField();
        $this->_childPactEventFieldEnumModel = new Application_Model_ActMdChildPactEventFieldEnum();
        $this->_childPactEventFieldLoopModel = new Application_Model_ActMdChildPactEventFieldLoop();
        $this->_fieldTypeModel = new Application_Model_ActMdFieldType();
        $this->_productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $this->view->title = "管理中心";
    }

    /**
     * 默认动作
     * 
     * @return void
     */
    public function indexAction()
    {
        

        //设置URL模板以及条件
        $urls = array();
        $vars = array();
        $wheres = array();

        $vars['expType'] = trim($this->_request->get('expType'))!='' ? trim($this->_request->get('expType')) : 'test';
        $vars['osName'] = trim($this->_request->get('osName'));
        $vars['dateType'] = trim($this->_request->get('dateType'))!='' ? trim($this->_request->get('dateType')) : 1;
        $vars['doType'] = trim($this->_request->get('doType'))!='' ? trim($this->_request->get('doType')) : 1;
        $vars['startTime'] = trim($this->_request->get('startTime'))!='' ? trim($this->_request->get('startTime')) : date('Y-m-d',strtotime("0 day"));
        $vars['userSign'] = trim($this->_request->get('userSign'))!='' ? trim($this->_request->get('userSign')) : '';
        $vars['eventId'] = trim($this->_request->get('eventId'))!='' ? trim($this->_request->get('eventId')) : '';
        $vars['pageSize'] = trim($this->_request->get('pageSize'))!='' ? intval(trim($this->_request->get('pageSize'))) : 30;
        $vars['eventSort'] = trim($this->_request->get('eventSort'))!='' ? trim($this->_request->get('eventSort')) : 'DESC';
        $vars['isAuto'] = trim($this->_request->get('isAuto'))!='' ? intval(trim($this->_request->get('isAuto'))) : 0;
        
        if ($this->_request->isPost()) {
            if (!$vars['expType']){
                echo $this->view->message('请选择操作环境!') ;
                exit;
            }
            if ((!$vars['startTime'])||(!preg_match('/^[\d]{4}-[\d]{1,2}-[\d]{1,2}$/', $vars['startTime']))){
                echo $this->view->message('请选择日志日期!') ;
                exit;
            }
            if (!$vars['osName']){
                echo $this->view->message('请选择操作系统!') ;
                exit;
            }
            if ($vars['userSign'] && strlen($vars['userSign'])<32){
                echo $this->view->message('userSign输入有误!') ;
                exit;
            }
            
        }
        
        //获取当前页码
        $pageSize = $vars['pageSize'];
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }
        
        $urls = $vars;

        $wheres[] = " reg.`productCode` = '{$this->_productCode}'";
        
        if ($vars['startTime'] != '') {
            $wheres[] = "  FROM_UNIXTIME(eventLog.`eventTime`/1000,'%Y-%m-%d') = '{$vars['startTime']}' ";
        }
        if ($vars['osName'] != '') {
            $wheres[] = " reg.`osName` = '{$vars['osName']}' ";
        }
        if ($vars['userSign'] != '') {
            $wheres[] = " eventLog.`userSign` = '{$vars['userSign']}' ";
        }
        
        $orderBy = " eventLog.eventTime  {$vars['eventSort']}";

        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        //$sql = "SELECT * FROM `{$this->_logModel->getTableName()}`{$where} ORDER BY {$orderBy}";
        $sql = "
                   SELECT eventLog.logId,eventLog.eventId,eventLog.eventTime,eventLog.userSign,eventLog.ip,reg.productCode,reg.osName,reg.sourceId,reg.sourceSubId,pe.eventName,pf.pactVersion
                   FROM `mob_act_md_log_event` AS eventLog
                   LEFT JOIN `mob_act_md_test_usersign` AS reg ON eventLog.userSign=reg.userSign
                   LEFT JOIN `mob_partner_product_platform` AS pf ON reg.productCode=pf.productCode AND reg.osName=pf.osName
                   LEFT JOIN `mob_act_md_child_pact_event` AS pe ON pf.pactVersion=pe.childVersion AND eventLog.eventId=pe.eventId
                   {$where}
                   ORDER BY {$orderBy}
                ";
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();

        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;
        
        $rows = $dbPaginator->getRows();
        
        $eventFieldRows = array();
        foreach ($rows as $row){
            $sql = "SELECT *,CONVERT(fieldSort,SIGNED) as sort  FROM mob_act_md_child_pact_event_field WHERE childVersion='{$row['pactVersion']}' AND eventId='{$row['eventId']}' ORDER BY  sort ASC ";
            $efRows = $this->_childPactEventFieldModel ->getAdapter()->fetchAll($sql);
            foreach ($efRows as $key => $field){
                $sql = "SELECT * FROM mob_act_md_log_event_field WHERE logId={$row['logId']} AND fieldSort={$field['fieldSort']} limit 1";
                $logFieldRow = $this->_logFieldModel ->getAdapter()->fetchRow($sql);
                $fieldValue = isset($logFieldRow['fieldValue']) ? $logFieldRow['fieldValue'] : '' ;
                
                $eventFieldRows[$row['logId']][$key]['fieldSort'] = $field['fieldSort'];
                $eventFieldRows[$row['logId']][$key]['fieldName'] = $field['fieldName'];
                $eventFieldRows[$row['logId']][$key]['note'] = $field['note'];
                $eventFieldRows[$row['logId']][$key]['fieldType'] = $field['fieldType'];
                $eventFieldRows[$row['logId']][$key]['fieldValue'] = $fieldValue;
                //枚举 类型
                if (in_array($field['fieldType'], array('E','N','F','G'))){
                	$enumValue = '';
                	//全局['E','F']
                    //局部['N','G']
                    $enum = trim($fieldValue)!='' ? intval(trim($fieldValue)) :0;
                    $sql = "SELECT * FROM mob_act_md_child_pact_event_field_enum WHERE childVersion='{$row['pactVersion']}' AND eventId ={$row['eventId']} AND fieldSort={$field['fieldSort']} AND fieldType='{$field['fieldType']}' AND enum={$enum} limit 1";
                    $logFieldEnumRow = $this->_childPactEventFieldEnumModel ->getAdapter()->fetchRow($sql);
                    $enumValue = isset($logFieldEnumRow['enumValue']) ? $logFieldEnumRow['enumValue'] : $fieldValue ;
                    $eventFieldRows[$row['logId']][$key]['fieldValue'] = $enumValue;
                }
                //循环 类型
                if ($field['fieldType']=='K'){
                	$loopTimes = trim($fieldValue)!='' ? intval(trim($fieldValue)) :1;
                    $sql = "SELECT * FROM mob_act_md_child_pact_event_field_loop WHERE childVersion='{$row['pactVersion']}' AND eventId ={$row['eventId']} AND fieldSort={$field['fieldSort']}";
                    $eflRows = $this->_childPactEventFieldLoopModel ->getAdapter()->fetchAll($sql);
                     for($i = 1; $i <= $loopTimes; $i++) {
	                    foreach ($eflRows as $val =>$fieldLoop){
	                        $sql = "SELECT * FROM mob_act_md_log_event_field_loop WHERE logId={$row['logId']} AND fieldSort={$field['fieldSort']} AND loopSort={$fieldLoop['loopFieldSort']} AND loopTimes={$i} limit 1";
	                        $logFieldLoopRow = $this->_logFieldLoopModel ->getAdapter()->fetchRow($sql);
	                        $eventFieldRows[$row['logId']][$key]['loop'][$logFieldLoopRow['loopTimes']][$logFieldLoopRow['loopSort']]['loopTimes'] = $logFieldLoopRow['loopTimes'];
	                        $eventFieldRows[$row['logId']][$key]['loop'][$logFieldLoopRow['loopTimes']][$logFieldLoopRow['loopSort']]['fieldName'] = $fieldLoop['fieldName'];
	                        $eventFieldRows[$row['logId']][$key]['loop'][$logFieldLoopRow['loopTimes']][$logFieldLoopRow['loopSort']]['note'] = $fieldLoop['note'];
	                        $eventFieldRows[$row['logId']][$key]['loop'][$logFieldLoopRow['loopTimes']][$logFieldLoopRow['loopSort']]['fieldType'] = $fieldLoop['fieldType'];
	                        $eventFieldRows[$row['logId']][$key]['loop'][$logFieldLoopRow['loopTimes']][$logFieldLoopRow['loopSort']]['loopValue'] = isset($logFieldLoopRow['loopValue']) ? $logFieldLoopRow['loopValue'] : '';
	                    }
                    }
                }
                //其它 类型
                
            }
        }
        

        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        $this->view->rows = $rows;
        $this->view->eventFieldRows = $eventFieldRows;
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
        $this->view->vars = $vars;
        
        //操作系统
        $pageVisitModel = new Application_Model_ActDayDataPagevisit();
        $osNameRows = $pageVisitModel ->getOsNameArray();
        $this->view->osNameRows = $osNameRows;
        
        //字段类型
        $fieldTypeRows = $this->_fieldTypeModel->getKeyValues();
        $this->view->fieldTypeRows = $fieldTypeRows;
    }
    
    
    
    /**
     * 异常查看
     * 
     * @return void
     */
    public function receiveLogAction()
    {
        //设置URL模板以及条件
        $urls = array();
        $vars = array();
        $wheres = array();
        $vars['expType'] = trim($this->_request->get('expType'))!='' ? trim($this->_request->get('expType')) : 'test';
        $vars['startTime'] = trim($this->_request->get('startTime'))!='' ? trim($this->_request->get('startTime')) : '';
        $vars['level'] = trim($this->_request->get('level'))!='' ? trim($this->_request->get('level')) : '';
        $vars['pageSize'] = trim($this->_request->get('pageSize'))!='' ? intval(trim($this->_request->get('pageSize'))) : 30;
        
        //获取当前页码
        $pageSize = $vars['pageSize'];
        $pageNo = intval($this->_request->get('pageNo'));
        if (empty($pageNo)) {
            $pageNo = 1;
        }
        
        $urls = $vars;
        //$wheres[] = " `productCode` = '{$this->_productCode}'";
        
        if ($vars['startTime'] != '') {
            $wheres[] = "  time >= '{$vars['startTime']} 00:00:00' and time<= '{$vars['startTime']} 23:59:59' ";
        }
        if ($vars['level'] != '') {
            $wheres[] = " `level` = '{$vars['level']}' ";
        }
        $orderBy = " time  DESC";

        $urls['pageNo'] = '{page}';
        $urlTemplate = $this->view->projectUrl($urls);

        //获取总页数以及记录
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $receiveLogModel = new Application_Model_ActMdReceiveLog();
        $sql = "SELECT * FROM `{$receiveLogModel->getTableName()}`{$where} ORDER BY {$orderBy}";
       
        $dbPaginator = new Application_Model_DbPaginator($sql, $pageSize, $pageNo);
        $recordCount = $dbPaginator->getRecodCount();

        //获取分页html字符
        Zend_Loader::loadClass('Project_Paginator');
        $paginator = new Project_Paginator($recordCount, $pageSize, $pageNo);
        $paginator->urlTemplateContent = $urlTemplate;
        $rows = $dbPaginator->getRows();
        
        //分配view(分页处理后的记录集以及分页HTML字符)
        $this->view->pageString = $paginator->getPageString();
        $this->view->rows = $rows;
        $urls['pageNo'] = $pageNo;
        $this->view->pageUrl = $this->view->projectUrl($urls);
        $this->view->vars = $vars;
        
    }
    
    
    
}